import React, { PureComponent } from 'react';
import classnames from 'classnames';
import S from './index.less';

export default class extends PureComponent {
    static defaultProps = {
        onChange: () => {}, // 切换状态
        checked: false, // 是否开启
        disabled: false, // 是否禁用
        width: '1.04rem',
        height: '.64rem',
        px: false,
        className: '',
        theme: '',
    };

    onChange = e => {
        if (this.props.disabled) {
            return;
        }
        e.preventDefault(); // 阻止默认事件，防止点击穿透，外溢
        e.stopPropagation();
        this.props.onChange(e);
    };

    render() {
        const {
            checked, disabled, px, className
        } = this.props;
        // eslint-disable-next-line prefer-const
        let { width, height, theme } = this.props;
        if (px) {
            width = '52px';
            height = '32px';
        }

        const CLASS = classnames(
            {
                [S.switch]: true,
                [S.checked]: checked,
                [S.disabled]: disabled,
                [S[theme]]: theme,
            },
            className
        );
        const STYLE = {
            borderRadius: height,
            width,
            height,
        };
        return (
            <div className={CLASS} style={STYLE} {...{ [$.os.phone ? 'onTouchEnd' : 'onClick']: this.onChange }}>
                <div className={S.bgd} />
                <div className={S.circle} />
            </div>
        );
    }
}
